const app = getApp();

Page({
  data: {
    appointments: [],
    currentUser: null
  },

  onLoad() {
    // 注册到全局，以便 app.js 收到推送时调用
    app.doctorAppointmentPage = this; 
    
    this.setData({
      currentUser: app.globalData.userInfo
    });
  },

  onShow() {
    // 如果是医生角色，加载预约列表
    if (app.globalData.userInfo && app.globalData.userInfo.role === 'doctor') {
      this.loadAppointments();
    } else {
      wx.redirectTo({ url: '/pages/login/login' });
    }
  },

  // 及时刷新：加载预约列表
  loadAppointments() {
    const doctorId = app.globalData.userInfo.id;
    wx.showNavigationBarLoading();
    
    app.request(`/api/appointments/${doctorId}`).then(res => {
      this.setData({ appointments: res });
      wx.hideNavigationBarLoading();
    }).catch(err => {
      wx.hideNavigationBarLoading();
      wx.showToast({ title: '加载失败', icon: 'none' });
    });
  },
  
  // 模拟登出
  logout() {
    app.globalData.userInfo = null;
    app.globalData.token = null;
    if (app.globalData.stompClient) {
      app.globalData.stompClient.disconnect(() => {
        app.globalData.stompClient = null;
        console.log("STOMP Disconnected");
      });
    }
    wx.removeStorageSync('userInfo');
    wx.redirectTo({ url: '/pages/login/login' });
  },

  onUnload() {
    // 页面卸载时解除注册
    app.doctorAppointmentPage = null;
  }
});